const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 定义nodejs环境变量：决定使用 browsersList 的哪个环境
process.env.NODE_ENV = 'production';

// 复用loader
const commonCssLoader = [
  MiniCssExtractPlugin.loader, // 这个loader取代style-loader。作用：提取js中的css成单独文件
  'css-loader',
  /*
    css兼容性处理：postcss --> postcss-loader postcss-preset-env
    帮postcss找到package.json中browserslist里面的配置，通过配置加载指定的css兼容性样式
    "browserslist": {
      // 开发环境 --> 设置node环境变量：process.env.NODE_ENV = development
      "development": [
        "last 1 chrome version",
        "last 1 firefox version",
        "last 1 safari version"
      ],
      // 生产环境：默认是看生产环境
      "production": [
        ">0.2%",
        "not dead",
        "not op_mini all"
      ]
    }
  */
  {
    // 还需要在package.json中定义browserslist
    loader: 'postcss-loader',
    options: {
      ident: 'postcss',
      plugins: () => [require('postcss-preset-env')()]
    }
  }
];

module.exports = {
  mode: 'production',
  entry: {
    home: './src/test/webpack.js',
    // other: './src/order.js',
  },
  output: {
    filename: 'js/[name].js',
    path: path.resolve(__dirname, 'build').replace('config\\', ''),
    // 所有输出资源的公共路径  ===>路径前面加个~
    publicPath: '/',
    chunkFilename: 'js/[name]_chunk.js',
    // library: '[name]', // 整个库向外暴露的变量名
    // libraryTarget: 'window' // 变量名添加到哪个上 browser
    // libraryTarget: 'global' // 变量名添加到哪个上 node
    // libraryTarget: 'commonjs'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [...commonCssLoader]
      },
      {
        test: /\.less$/,
        use: [...commonCssLoader, 'less-loader']
      },
      /*
        语法检查： eslint-loader  eslint
          注意：只检查自己写的源代码，第三方的库是不用检查的
          设置检查规则：
            package.json中eslintConfig中设置~
              "eslintConfig": {
                "extends": "airbnb-base"
              }
            airbnb --> eslint-config-airbnb-base  eslint-plugin-import eslint
      */
      // {
      //   // 在package.json中eslintConfig --> airbnb
      //   test: /\.js$/,
      //   exclude: /node_modules/,
      //   include: path.resolve(__dirname, 'src').replace('config\\', ''),
      //   /*enforce: 'pre', 优先执行
      //     正常来讲，一个文件只能被一个loader处理。
      //     当一个文件要被多个loader处理，那么一定要指定loader执行的先后顺序：
      //       先执行eslint 在执行babel
      //    */
      //   enforce: 'pre',
      //   loader: 'eslint-loader',
      //   options: {
      //     fix: true
      //   }
      // },
      /*
        js兼容性处理：babel-loader @babel/core
          1. 基本js兼容性处理 --> @babel/preset-env
            问题：只能转换基本语法，如promise高级语法不能转换
          2. 全部js兼容性处理 --> @babel/polyfill
            问题：我只要解决部分兼容性问题，但是将所有兼容性代码全部引入，体积太大了~
          3. 需要做兼容性处理的就做：按需加载  --> core-js
      */
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          // 预设：指示babel做怎么样的兼容性处理
          presets: [
            [
              '@babel/preset-env',
              {
                // 按需加载
                useBuiltIns: 'usage',
                // 指定core-js版本
                corejs: {version: 3},
                // 指定兼容性做到哪个版本浏览器
                targets: {
                  chrome: '60',
                  firefox: '50',
                  ie: '9',
                  safari: '10',
                  edge: '17'
                }
              }
            ]
          ]
        }
      },
      {
        test: /\.(jpg|png|gif)/,
        loader: 'url-loader',
        options: {
          limit: 8 * 1024,
          name: '[hash:10].[ext]',
          outputPath: 'images',
          esModule: false
        }
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        exclude: /\.(js|css|less|html|jpg|png|gif)/,
        loader: 'file-loader',
        options: {
          outputPath: 'files'
        }
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      // 对输出的css文件进行重命名
      filename: 'css/build.css'
    }),
    // 压缩css
    new OptimizeCssAssetsWebpackPlugin({
      filename: 'css/[name].css',

    }),
    // html-webpack-plugin 默认会创建一个HTML，自动打包输出的所有资源（js/css）,需要有结构的HTML文件
    new HtmlWebpackPlugin({
      // 压缩代码 collapseWhitespace:移除空格;  removeComments移除注释
      // minify: {collapseWhitespace: true, removeComments: true},
      chunks: ['webpack']
    }),
    // new HtmlWebpackPlugin({
    //   template: './src/index.html',
    //   minify: {collapseWhitespace: true, removeComments: true},
    //   chunks: ['other']
    // })
  ]
};


const {resolve} = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

/*
  {
    name: 'webpack',
    entry: './src/test/webpack.js',
    title: 'webpack',
    template: './src/test/webpack.html',
    filename: 'webpack.html',
    chunks: ['webpack'],
  },
 */
const pages = [
  {name: undefined, entry: undefined, title: undefined, template: undefined, filename: undefined, chunks: undefined},
  {
    entry: './src/test/webpack.js',
    template: './src/test/webpack.html',
    filename: 'webpack.html',
  },
  {
    entry: './src/test/webpack2.js',
    template: './src/test/webpack2.html',
    filename: 'webpack2.html',
  }
]
const plugins = [];
const entry = {};

pages.forEach(value => {
  if (!value.entry){
    entry[value.name || value.filename.replace('.html', '')] = value.entry

    plugins.push(new HtmlWebpackPlugin({
      title: value.title || value.filename.replace('.html', ''),
      template: value.template || undefined,
      filename: value.filename,
      chunks: value.chunks || [value.filename.replace('.html', '')],
      // minify: {collapseWhitespace: true, removeComments: true},
    }))
  }
})

webpackConfig = {
  mode: 'production',
  devServer: {contentBase: resolve(__dirname, 'build'), compress: true, port: 3000, open: true},
  entry,
  output: {
    filename: 'js/[name].js',
    path: resolve(__dirname, 'build'),
    publicPath: '',
    chunkFilename: 'js/chunk[name].js',
  },
  module: {
    rules: [
      {
        test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader', {
          // loader: 'postcss-loader', options: {ident: 'postcss', plugins: () => [require('postcss-preset-env')()]}
        }]
      },
      // {
      //   test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: {
      //     presets: [[
      //       '@babel/preset-env', {useBuiltIns: 'usage', corejs: {version: 3}, targets: {chrome: '60', firefox: '50', ie: '9', safari: '10', edge: '17'}}
      //     ]]
      //   }
      // },
      {test: /\.(jpg|png|gif)/, loader: 'url-loader', options: {limit: 8 * 1024, name: '[hash:3].[ext]', outputPath: 'images', esModule: false}},
      {test: /\.html$/, loader: 'html-loader'},
      {exclude: /\.(js|css|less|html|jpg|png|gif)/, loader: 'file-loader', options: {outputPath: 'files'}}
    ]
  },
  plugins: [
    ...plugins,
    new MiniCssExtractPlugin({
      filename: 'css/[name].css'
    }),
    new OptimizeCssAssetsWebpackPlugin(),
  ]
}

module.exports = webpackConfig
